<template>
    <div>
        <app-search>
            <el-form :model="quot" :label-position="$store.labelPosition"
                     label-width="30%" ref="quot" :rules="rules">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="报价单号：" prop="quotNo">
                            <el-input v-model="quot.quotNo" :disabled="isView"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="日期：" prop="quotDt">
                            <el-date-picker type="date" placeholder="报价日期" v-model="quot.quotDt"
                                            :disabled="isView" value-format="yyyy-MM-dd"
                                            format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户：" prop="custId">
                            <el-select v-model="quot.custId" filterable  clearable placeholder="请选择客户"
                                       @change="changeCustomer()" :disabled="isView">
                                <el-option v-for="cust in customers" :key="cust.id"
                                           :label="cust.name" :value="cust.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人：" prop="contactId">
                            <el-select v-model="quot.contactId" clearable placeholder="请选择联系人"
                                       :disabled="isView">
                                <el-option v-for="contact in contacts" :key="contact.id"
                                           :label="contact.name" :value="contact.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="业务员：" v-if="showSells" prop="sellMan">
                            <el-select v-model="quot.sellMan" clearable placeholder="请选择业务员"
                                       :disabled="isView">
                                <el-option v-for="sell in sells" :key="sell.userId"
                                           :label="sell.username" :value="sell.userId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="isEditQuot">
                        <el-form-item label="总价：">
                            {{totalPrice}}
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注：" label-width="15%">
                            <el-input type="textarea" :row="3" v-model="quot.remark"
                                      :disabled="isView"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    </el-col>
                </el-row>

                <el-row >
                    <el-col :span="24">
                        <el-form-item label-width="15%">
                            <el-button type="edit" icon="fa fa-save" @click="submitForm()" v-if="!isView">
                                保存
                            </el-button>

                            <el-button type="edit" icon="el-icon-plus" v-if="isEditQuot && !isView"
                                       @click="showAddQuotItem()">添加产品</el-button>
                            <el-button type="danger" icon="el-icon-delete" v-if="isEditQuot && !isView"
                                       @click="deleteSelectedProds()" >删除产品</el-button>

                            <el-button type="primary" icon="el-icon-back" @click="cancel()">
                                返回
                            </el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </app-search>

        <template v-if="isEditQuot">
        <quot-item-list v-bind:tableData="quotItems"></quot-item-list>

        <quot-item-edit v-bind:quotItem="quotItem"></quot-item-edit>
        </template>

    </div>

</template>

<script>
import QuotItemEdit from './quot_item_edit';
import QuotItemList from './quot_item_list';
import { mapState } from 'vuex';

export default {
    name: "QuotEdit",
    components: {QuotItemList, QuotItemEdit},
    data() {
        return {
            quot: {},
            contacts: [],
            tableData: {
                loading: true,
                body: []
            },
            rules:{
                quotNo:[{ required: true, message: '请输入报价单号', trigger: 'blur' }],
                quotDt:[{ required: true, message: '请输入日期', trigger: 'blur' }],
                custId:[{ required: true, message: '请选择客户', trigger: ['blur'] }],
                contactId:[{ required: true, message: '请选择联系人', trigger: ['blur'] }],
                sellMan:[{ required: true, message: '请选择业务员', trigger: ['blur'] }]
            }
        }
    },
    mounted() {
        console.log("isView: ", this.$store.isView)
        this.initQuotation()
    },

    methods: {
        // 获取报价数据
        async initQuotation() {
            let res = await this.$axios.get(`/sell/quot/initQuotation/${this.quotId}`);
            console.log("返回报价信息：", res);

            this.quot = res.result.quot;
            this.contacts = res.result.contactList;
            this.tableData.loading = false;
            this.$store.commit("quot/Set_Quot_Items", res.result.itemList);
        },

        showAddQuotItem(){
            this.$store.commit("quot/Show_Add_Quot_Item")
        },

        submitForm(){
            this.$refs['quot'].validate((valid) => {
                if(valid){
                    this.saveQuot();
                }
            });
        },

        async saveQuot(){
            if(this.isEditQuot){
                await this.$axios.post('/sell/quot/edit', this.quot);
                this.$myMsg.success('成功修改报价信息。');
            }else{
                let res = await this.$axios.post('/sell/quot/add', this.quot);
                this.$myMsg.success('成功创建报价信息。请增加产品信息。');
                this.quot = res.result;
                this.$store.dispatch('quot/showEditQuot', this.quot.id)
            }
        },

        async changeCustomer(){
            let res = await this.$axios.get(`/company/contact/findByCompanyId/${this.quot.custId}`);
            console.log("返回的联系人列表：", res);
            this.contacts = res.result;
            this.quot.contactId = "";
        },

        async deleteSelectedProds() {
            let deletedIds = "";
            this.selectedItems.forEach( item => {
                deletedIds += item.id + ",";
            });
            //console.log("deleted cd items: ", deletedIds);
            await this.$axios.delete(`/sell/quot/quotItem/batchRemove/${deletedIds}`);

            this.$store.dispatch("quot/removeQuotItems");
        },

        cancel(){
            this.$store.commit("quot/Set_Show_Edit_Quot", false);
        }

    },

    computed: {
        ...mapState({
            customers: state => state.quot.initPageData.customers,
            sells: state => state.quot.initPageData.sells,
            showSells: state => state.quot.initPageData.showSells,
            quotItems: state => state.quot.quotItems,
            quotId: state => state.quot.quotId,
            quotItem: state => state.quot.quotItem,
            selectedItems: state => state.quot.selectedItems,
            isView: state => state.quot.isView
        }),

        isEditQuot(){
            return this.quotId > -1
        },

        totalPrice(){
            let total = 0.00;
            if(this.quotItems){
                console.log("当前产品：", this.quotItems);
                for(let i = 0; i < this.quotItems.length; i++){
                    total = total + this.quotItems[i].price * this.quotItems[i].num;
                }
            }

            return total;
        }
    }
}
</script>

